package com.drought.rained.auth;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.drought.rained.R;
import com.drought.rained.base.BaseTitleActivity;
import com.drought.rained.bean.AuthInfoDataLJ;
import com.drought.rained.bean.IdentityDataLJ;
import com.drought.rained.business.AuthRouterLJ;
import com.drought.rained.business.GlideImageLoaderLJ;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.camera.CameraActivityLJ;
import com.drought.rained.camera.PicturePreviewActivityLJ;
import com.drought.rained.common.ConstantLJ;
import com.drought.rained.mvpview.ImgMvpViewLJ;
import com.drought.rained.mvpview.RealNameAuthMvpViewLJ;
import com.drought.rained.permission.IPermissonLJ;
import com.drought.rained.permission.PermissionLJ;
import com.drought.rained.presenter.ImgPresenterLJ;
import com.drought.rained.presenter.RealNameAuthPresenterLJ;
import com.drought.rained.response.AuthInfoResponseLJ;
import com.drought.rained.response.BlankResponseLJ;
import com.drought.rained.response.CompareResultResponseLJ;
import com.drought.rained.response.IdentityResponseLJ;
import com.drought.rained.utils.FileUtilsLJ;
import com.drought.rained.utils.ImageUtilsLJ;
import com.drought.rained.utils.RegularExpressionLJ;
import com.drought.rained.utils.ToastUtilsLJ;
import com.drought.rained.utils.UploadImageUtilLJ;
import com.drought.rained.view.ShootingDialogLJ;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(name = "身份证认证", path = RouterMapLJ.REAL_NAME_AUTH_PAGE)
public class RealNameActivityLJ extends BaseTitleActivity implements RealNameAuthMvpViewLJ, ImgMvpViewLJ, IPermissonLJ {

    @BindView(R.id.lauout_one)
    LinearLayout lauout_one;
    @BindView(R.id.lauout_two)
    LinearLayout lauout_two;
    @BindView(R.id.et_id_name)
    EditText et_id_name;
    @BindView(R.id.et_id_number)
    EditText et_id_number;
    @BindView(R.id.et_birth_date)
    EditText et_birth_date;
    @BindView(R.id.iv_positive)
    ImageView iv_positive;
    @BindView(R.id.iv_nagative)
    ImageView iv_nagative;
    @BindView(R.id.tv_next_step)
    TextView tv_next_step;
    @BindArray(R.array.identity)  //绑定string里面array数组
            String[] identity;

    @Autowired(name = ConstantLJ.IS_BACK)
    boolean is_back;
    private RealNameAuthPresenterLJ realNameAuthPresenter;
    private ImgPresenterLJ imgPresenter;
    private PermissionLJ permission;
    private DatePicker birthdayPicker;

    private IdentityDataLJ.IdentityBean identityBean; // 身份证信息
    private IdentityDataLJ.ImageInfoBean imageInfoBeanPositive;
    private IdentityDataLJ.ImageInfoBean imageInfoBeanNagative;
    private List<IdentityDataLJ.ImageInfoBean> imageInfoParams;
    private int pass = 2;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {

        permission = new PermissionLJ(this, this);
        realNameAuthPresenter = new RealNameAuthPresenterLJ(this);
        imgPresenter = new ImgPresenterLJ(this);
        if (UserInfoLJ.isShowUserInformation())
            realNameAuthPresenter.getIdentityInfo();
        if (is_back) {
            tv_next_step.setText(R.string.save_change);
        }

    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_real_name;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.auth_id_card_page_name);
    }

    @OnClick({R.id.tv_next_step, R.id.iv_positive, R.id.iv_nagative, R.id.et_birth_date})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_positive:
                showTips();
                break;
            case R.id.iv_nagative:
                permission.authPermisson(ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE);
                break;
            case R.id.tv_next_step:
//                commit();
                String str = checkForm();
                if (!TextUtils.isEmpty(str)) {
                    Toast.makeText(RealNameActivityLJ.this, str, Toast.LENGTH_SHORT).show();
                    return;
                }
                identityBean.setRealName(et_id_name.getText().toString());
                identityBean.setIdentityCardNum(et_id_number.getText().toString());
                identityBean.setBirthday(et_birth_date.getText().toString());

                if (imageInfoBeanPositive != null && imageInfoBeanNagative != null) {
                    imageInfoParams = new ArrayList<>();
                    imageInfoParams.add(imageInfoBeanPositive);
                    imageInfoParams.add(imageInfoBeanNagative);
                    realNameAuthPresenter.saveIdentity(identityBean, imageInfoParams, pass);
                    showLoadingView();
                }
//                showDialog();
                break;
            case R.id.et_birth_date:
                pickerBirthDay();
                break;
        }

    }

    private void pickerBirthDay() {
        if (birthdayPicker == null) {
            //24小时值
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(new Date());
            birthdayPicker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
            birthdayPicker.setRangeStart(Integer.parseInt(year) - 50, 1, 1);//日期起点
            birthdayPicker.setSelectedItem(Integer.parseInt(year) - 25, 1, 1); // 设置默认选中值
            birthdayPicker.setRangeEnd(Integer.parseInt(year) - 15, 1, 1);//日期终点
            birthdayPicker.setLabel(getStringResource(R.string.year_unit),
                    getStringResource(R.string.month_unit),
                    getStringResource(R.string.day_unit));
            birthdayPicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {

                    et_birth_date.setText(year + "." + month + "." + day);
                }
            });
        }
        birthdayPicker.show();
    }

    public void commit() {
        if (iv_positive.getDrawable() == null) {
            ToastUtilsLJ.showShort(this, R.string.auth_id_card_positive_hint);
            return;
        }
        if (iv_nagative.getDrawable() == null) {
            ToastUtilsLJ.showShort(this, R.string.auth_id_card_positive_half_body_hint);
            return;
        }

        if (identityBean == null) {
            ToastUtilsLJ.showShort(this, R.string.auth_id_card_positive_hint);
            return;
        }

        realNameAuthPresenter.imgCompare(imageInfoBeanPositive.getImagePath(), imageInfoBeanNagative.getImagePath());
        showLoadingView();

    }


    public void compressImgAndDisPlay(Uri sourceImgUri, final int compressType) {

        Luban.with(this)
                .ignoreBy(500)
                .load(sourceImgUri)
                .setTargetDir(FileUtilsLJ.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        showLoadingView();
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (compressType == ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE) {
                            imgPresenter.uploadIdentityCard(file);
                        } else if (compressType == ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE) {
                            imgPresenter.uploadImg(compressType,file);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingView();
                    }
                }).launch();

    }

    public void compressImgAndDisPlayForFileString(String filePath, final int compressType) {
        Luban.with(this)
                .ignoreBy(500)
                .load(filePath)
                .setTargetDir(FileUtilsLJ.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        showLoadingView();
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (compressType == ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE) {
                            imgPresenter.uploadIdentityCard(file);
                        } else if (compressType == ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE) {
                            imgPresenter.uploadImg(compressType, file);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingView();
                    }
                }).launch();

    }


    private String checkForm() {
        if (TextUtils.isEmpty(et_id_name.getText().toString().trim())) {
            return getStringResource(R.string.auth_type_real_name_hint);
        } else if (TextUtils.isEmpty(et_id_number.getText().toString().trim())) {
            return getStringResource(R.string.auth_type_real_id_card_num_hint);
        } else if (TextUtils.isEmpty(et_birth_date.getText().toString().trim())) {
            return getStringResource(R.string.auth_type_birthday_hint);
        }

        String check = RegularExpressionLJ.checkRegularExpression(et_id_number.getText().toString().trim()
                , RegularExpressionLJ.idnum, getStringResource(R.string.auth_type_id_num_error));
        if (!TextUtils.isEmpty(check)) {
            return check;
        }

        return null;
    }

    private void showTips() {
        final ShootingDialogLJ shootingDialog = new ShootingDialogLJ(this, getStringResource(R.string.auth_id_card_shopting_title));
        shootingDialog.show();
        shootingDialog.setOnClickListener(new ShootingDialogLJ.CallBack() {
            @Override
            public void onConfirm() {
                permission.authPermisson(ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE);
                shootingDialog.hide();
            }
        });
    }

    @Override
    public void onGetDataNext(BlankResponseLJ response) {
        dismissLoadingView(); // 提交
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            // 跳转
            AuthRouterLJ.getInstance().jumpNextPager(RealNameActivityLJ.this, RouterMapLJ.REAL_NAME_AUTH_PAGE);
        } else {
            ToastUtilsLJ.showShort(RealNameActivityLJ.this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(AuthInfoResponseLJ response) {
        dismissLoadingView(); // 获取
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            fillImgView(response.getData().getIdentity());
        } else {
            ToastUtilsLJ.showShort(RealNameActivityLJ.this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(CompareResultResponseLJ response) {
        dismissLoadingView();
        pass = response.getData().getPass();
        if (response.getData().getCompareStatus()) {
            if (!is_back) {
                lauout_one.setVisibility(View.GONE);
                et_id_name.setText(identityBean.getRealName());
                et_id_number.setText(identityBean.getIdentityCardNum());
                et_birth_date.setText(identityBean.getBirthday());
                lauout_two.setVisibility(View.VISIBLE);
                tv_next_step.setVisibility(View.VISIBLE);
            } else {
                imageInfoParams = new ArrayList<>();
                imageInfoParams.add(imageInfoBeanPositive);
                imageInfoParams.add(imageInfoBeanNagative);

                realNameAuthPresenter.saveIdentity(identityBean, imageInfoParams, pass);
            }
        } else {
            iv_nagative.setImageDrawable(null);
            ToastUtilsLJ.showShort(this, response.getMessage());
        }

    }

    private void fillImgView(AuthInfoDataLJ.IdentityBean identityBean) {
        List<AuthInfoDataLJ.IdentityBean.IdentityImagesBean> imgList = identityBean.getIdentityImages();
        if (imgList == null || imgList.size() == 0) return;
        for (AuthInfoDataLJ.IdentityBean.IdentityImagesBean image : imgList) {
            if (ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE == image.getFileType()) {
                GlideImageLoaderLJ.LoadImage(this, image.getImageUrl(), iv_positive);
            } else if (ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE == image.getFileType()) {
                GlideImageLoaderLJ.LoadImage(this, image.getImageUrl(), iv_nagative);
            }
        }

        this.identityBean = new IdentityDataLJ.IdentityBean(identityBean);
    }

    @Override
    public void onGetDataNext(IdentityResponseLJ identityResponse, int... type) {
        dismissLoadingView();
        if (identityResponse.getStatus() == ConstantLJ.HTTP_OK) {
            if (type.length > 0 && type[0] == 1) {
                identityBean = identityResponse.getData().getIdentity();
                imageInfoBeanPositive = identityResponse.getData().getImageInfo();
            } else {
                imageInfoBeanNagative = identityResponse.getData().getImageInfo();
            }
            if (imageInfoBeanPositive != null && imageInfoBeanNagative != null) {
                commit(); // 上次完身份证显示信息
            }

        } else {
            ToastUtilsLJ.showShort(RealNameActivityLJ.this, identityResponse.getMessage());
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @Override
    public void onSuccess(int result) {
        if (result == ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE) {
            Intent intent = new Intent(this, CameraActivityLJ.class);
            intent.putExtra(CameraActivityLJ.TYPE, CameraActivityLJ.TYPE_ID_CARD);
            startActivityForResult(intent, result);
        } else if (result == ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE) {
            Intent intent = new Intent(this, CameraActivityLJ.class);
            intent.putExtra(CameraActivityLJ.TYPE, CameraActivityLJ.TYPE_PERSON);
            startActivityForResult(intent, result);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x1234) {
            final String filePath = data.getStringExtra("filename");
            File file =new File(filePath);
            Uri  uri = Uri.fromFile(file);
            // 在这判断获取的图片文件大小是否为0 分别处理
            if (file.length() > 0) {
                switch (requestCode) {
                    case ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE:
                        iv_positive.setImageURI(uri);
                        compressImgAndDisPlay(uri,requestCode);
                        break;
                    case ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE:
                        iv_nagative.setImageURI(uri);
                        compressImgAndDisPlay(uri,requestCode);
                        break;
                }
            } else {
                Bitmap bitmap = ImageUtilsLJ.bytes2Bitmap(PicturePreviewActivityLJ.getImage());
                if (null == bitmap || bitmap.getAllocationByteCount() == 0) {
                    bitmap = BitmapFactory.decodeFile(data.getStringExtra("filename"));
                }
                if (null != bitmap && bitmap.getAllocationByteCount() > 0) {
                    bitmap = UploadImageUtilLJ.getUploadNeedBitmapBYSize(bitmap);
                    if (UploadImageUtilLJ.checkBitmapSize(bitmap)) {

                        switch (requestCode) {
                            case ConstantLJ.PIC_TYPE_ID_CARD_POSITIVE:
                                iv_positive.setImageBitmap(bitmap);
                                break;
                            case ConstantLJ.PIC_TYPE_ID_CARD_NAGATIVE:
                                iv_nagative.setImageBitmap(bitmap);
                                break;
                            default:
                                break;
                        }
                        imgPresenter.uploadIdentityCardForBitmap(requestCode,bitmap);
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                compressImgAndDisPlayForFileString(filePath, ConstantLJ
                                        .PIC_TYPE_ID_CARD_POSITIVE);
                            }
                        }, 2500);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            compressImgAndDisPlayForFileString(filePath, ConstantLJ
                                    .PIC_TYPE_ID_CARD_POSITIVE);
                        }
                    }, 1500);
                }
            }
        }
    }

}
